﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Common;
using Wuqi.Webdiyer;
using AjaxPro;
using Mang24k99.Model.GOLD;
using Mang24k99.Business.GOLD;
using Mang24k99.Business.COMM;
using Mang24k99.Business.CLMN;
using Mang24k99.Model.COMM;
using Mang24k99.Model.CLMN;
namespace Mang24k99.Web.GOLD.KtGoldSusandres
{
    public partial class ListEdit : System.Web.UI.Page
    {
        protected string RootPath = VirtualPathUtility.ToAbsolute("~/");
        string _AspNetCostumHtmlName = "AspNetCostumHtmlName";
        public string AspNetCostumHtml
        {
            get
            {
                return ViewStateHelper.GetString(this.ViewState, _AspNetCostumHtmlName);
            }
            set
            {
                ViewStateHelper.SetViewState(this.ViewState, value, _AspNetCostumHtmlName);
            }
        }
        string _AddName = "Add";
        string _ModifyName = "Modify";
        string _NavTextName = "NavText";
        /// <summary>
        /// 分页的名称
        /// </summary>
        string _PageIndexName = "pageIndex";
        /// <summary>
        /// 操作的名称
        /// </summary>
        string _OpName = "op";
        /// <summary>
        /// 主键的名称
        /// </summary>
        string _IDName = "ID";
        /// <summary>
        /// Gets or sets the nav text.(保存lblNav.text的初始值)
        /// </summary>
        /// <value>The nav text.</value>
        public string NavText
        {
            get
            {
                return ViewStateHelper.GetString(ViewState, _NavTextName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _NavTextName);
            }
        }
        /// <summary>
        /// Gets or sets the index of the page.(保存修改时当前页)
        /// </summary>
        /// <value>The index of the page.</value>
        public int? PageIndex
        {
            get
            {
                return ViewStateHelper.GetInt(ViewState, _PageIndexName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _PageIndexName);
            }
        }
        /// <summary>
        /// Gets or sets the primary ID.(主键id)
        /// </summary>
        /// <value>The primary ID.</value>
        public int? PrimaryID
        {
            get
            {
                return ViewStateHelper.GetInt(ViewState, _IDName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _IDName);
            }
        }
        /// <summary>
        /// Gets or sets the op.(操作符)
        /// </summary>
        /// <value>The op.</value>
        public string Op
        {
            get
            {
                return ViewStateHelper.GetString(ViewState, _OpName);
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, _OpName);
            }
        }

        /// <summary>
        /// Gets or sets the auth.(权限)
        /// </summary>
        /// <value>The auth.</value>
        public string Auth
        {
            get
            {
                return ViewStateHelper.GetString(ViewState, "Auth");
            }
            set
            {
                ViewStateHelper.SetViewState(ViewState, value, "Auth");
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (string.IsNullOrEmpty(Auth))
            //{
            //    Auth = CommonGrant.Auth.GetPageAuth(this);
            //    if (string.IsNullOrEmpty(Auth))
            //    {
            //        return;
            //    }
            //}
            //else
            //{
            //    CommonGrant.Auth.RefreshPageAuth(this);
            //}
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Mang24k99.Business.GOLD.BKtGoldSusandres));
            if (!IsPostBack)
            {
                if (Request.QueryString["pageIndex"] != null)
                {
                    ddlKtCommCodelist.SelectedValue = Request.QueryString["pageIndex"].ToString();
                } 
                
                BindDDL();
                InitialParameter();

            }
        }

        /// <summary>
        /// Binds the ASP net pager.(绑定分页控件)
        /// </summary>
        private void BindAspNetPager()
        {
            AspNetPager aspNetPager = this.AspNetPager1;
            int RecordCount = BKtGoldSusandres.CountAll();
            aspNetPager.RecordCount = RecordCount;
            aspNetPager.CustomInfoHTML = string.Format(this.AspNetCostumHtml, aspNetPager.PageCount);
            if (!IsPostBack)
            {
                int pageIndex;
                try
                {
                    pageIndex = int.Parse(this.Request.QueryString["pageIndex"]);
                    this.AspNetPager1.CurrentPageIndex = pageIndex;

                }
                catch (Exception)
                {
                }
            }
        }
        /// <summary>
        /// Binds the reapert.(绑定列表控件)
        /// </summary>
        private void BindReapert()
        {
            AspNetPager aspNetPager = this.AspNetPager1;
            Repeater repeater = this.Repeater1;
            int maxRecord = aspNetPager.PageSize;
            int startRecord = aspNetPager.StartRecordIndex - 1;
            object dataSource = BKtGoldSusandres.FindALLSlicedAll(startRecord, maxRecord);
            repeater.DataSource = dataSource;
            repeater.DataBind();
        }
        /// <summary>
        /// Handles the PageChanged event of the AspNetPager1 control.(列表改变时候)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindAspNetPager();
            BindReapert();
            //CommonGrant.WebControlEnable.SetEnable(this, Auth);
        }
        /// <summary>
        /// Handles the PreRender event of the Repeater1 control.(列表程序之前)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Repeater1_PreRender(object sender, EventArgs e)
        {
            //Repeater repeater = (Repeater)sender;
            //IEnumerable repeaterObject=repeater.Items;
            //集体加客户端属性
            //PageOp.SetRepeaterAttributes(repeaterObject, "btnDelete", "onclick", "return ConfirmDelete()");
        }
        /// <summary>
        /// Handles the ItemCommand event of the Repeater1 control.(列表控件字段按钮事件)
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterCommandEventArgs"/> instance containing the event data.</param>
        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Button btnSource = e.CommandSource as Button;//事件按钮
            Button btnDelete = e.Item.FindControl("btnDelete") as Button;//删除按钮
            Button btnModify = e.Item.FindControl("btnModify") as Button;
            if (btnDelete.Enabled == false)
            {//防止客户端修改disable属性
                return;
            }
            if (btnModify.Enabled == false)
            {//防止客户端修改disable属性
                return;
            }
            object id;
            try
            {
                id = int.Parse(e.CommandArgument.ToString());
            }
            catch (Exception)
            {
                //转换失败忽略
                return;
            }
            if (btnSource.CommandName == btnDelete.CommandName)//若为删除按钮
            {
                Delete(id);
                Op = _AddName;
                MessageBox.Redirect(this, GetListUrl(this.AspNetPager1.CurrentPageIndex));
            }
            if (btnSource.CommandName == btnModify.CommandName)//为修改按钮
            {
                Op = _ModifyName;
                PrimaryID = TypeHelper.GetInt(id);
                PageIndex = this.AspNetPager1.CurrentPageIndex;
                BindData();
            }
        }
        protected void Delete(object id)
        {
            MKtGoldSusandres mKtGoldSusandres = BKtGoldSusandres.Find(id);
            if (mKtGoldSusandres != null)
            {
                BKtGoldSusandres.Delete(mKtGoldSusandres);
            }
        }
        protected void lnkbtnAdd_Click(object sender, EventArgs e)
        {
            GoUrl(_AddName);
        }
        private void GoUrl(string op)
        {
            string url = GetUrl(op);
            Response.Redirect(url, true);
        }
        private string GetUrl(string op)
        {
            int pageIndex = this.AspNetPager1.CurrentPageIndex;
            string url = "Edit.aspx" + "?" + "pageIndex=" + pageIndex + "&" + "op=" + op;
            return url;
        }
        protected void lnkbtnList_Click(object sender, EventArgs e)
        {
            GoServerListUrl(1);

        }
        /// <summary>
        /// Initials the parameter.(接受必要参数,无参数退出)
        /// </summary>
        private void InitialParameter()
        {
            this.btnSave.Attributes.Add("onclick", "return checkAll();");
            if (string.IsNullOrEmpty(Op))
            {
                Op = _AddName;
            }
            //string strNavText = CommonGrant.Auth.GetPageNavText(this);
            string strNavText = "";

            NavText = strNavText + this.lblNav.Text;
            this.Title = strNavText + "   后台管理系统";

            
            //PrimaryID = RequestHelper.GetInt(this, _IDName);
            //if (!PageIndex.HasValue)
            //{
            //    Response.End();
            //}


            BindData();
        }
        /// <summary>
        /// Binds the data.(绑定基础数据)
        /// </summary>
        private void BindData()
        {
            this.AspNetCostumHtml = this.AspNetPager1.CustomInfoHTML;
            //BindDDL();            
            if (BKtGoldSusandres.Count(int.Parse(ddlKtCommCodelist.SelectedValue.ToString()))>0)
            {  
                Op = "Modify";
                PrimaryID = BKtGoldSusandres.FindAnyOne(int.Parse(ddlKtCommCodelist.SelectedValue.ToString())).ID;
            }
            else
            {
                Op = "Add";
                txtRestainDayone.Text = "-";
                txtRestainDaytwo.Text = "-";
                txtRestainWeekone.Text = "-";
                txtRestainWeektwo.Text = "-";
                txtSustainDayone.Text = "-";
                txtSustainDaytwo.Text = "-";
                txtSustainWeekone.Text = "-";
                txtSustainWeektwo.Text = "-";
            }

            Castle.Components.Validator.RunWhen runWhen = Castle.Components.Validator.RunWhen.Insert;
            if (StringHelper.Compare(Op, _AddName))
            {
                this.lblNav.Text = string.Format(NavText, "新增");
                this.btnSave.Text = "新 增";
                AspNetPager1_PageChanged(null, null);
            }
            else if (StringHelper.Compare(Op, _ModifyName))
            {
                if (!PrimaryID.HasValue)
                {
                    Response.End();
                }
                this.btnSave.Text = "修 改";
                SetNavTextToModify();
                BindEdit();
            }
            else
            {
                Response.End();
                return;
            }
            Type typeMode = typeof(MKtGoldSusandres);
            WebHelper.SetWebControlAttributes(runWhen, typeMode, this.Controls[0].FindControl("form1").Controls[0].Controls);
        }
        /// <summary>
        /// Sets the nav text to modify.
        /// </summary>
        private void SetNavTextToModify()
        {
            this.lblNav.Text = string.Format(NavText, "修改");
        }
        /// <summary>
        /// Binds the DDL.(绑定ddl)
        /// </summary>
        private void BindDDL()
        {
            IList<MKtCommCodeList> modelsParentKtCommCodelistByBreedCode = BKtCommCodeList.FindAll();
            //MKtCommCodeList valueParentKtCommCodelistByBreedCode = new MKtCommCodeList();
            //valueParentKtCommCodelistByBreedCode.CODE_NO = 0;
            //valueParentKtCommCodelistByBreedCode.CODE_CNAME = "--请选择--";
            //IList<MKtCommCodeList> sourceModelsParentKtCommCodelistByBreedCode = ListHelper<MKtCommCodeList>.GetList(modelsParentKtCommCodelistByBreedCode, valueParentKtCommCodelistByBreedCode);
            IList<MKtCommCodeList> sourceModelsParentKtCommCodelistByBreedCode = modelsParentKtCommCodelistByBreedCode;
            
            this.ddlKtCommCodelist.DataSource = sourceModelsParentKtCommCodelistByBreedCode;
            this.ddlKtCommCodelist.DataTextField = "CODE_CNAME";
            this.ddlKtCommCodelist.DataValueField = "CODE_NO";
            this.ddlKtCommCodelist.DataBind();


        }
        /// <summary>
        /// Binds the edit.(绑定编辑页面)
        /// </summary>
        private void BindEdit()
        {
            MKtGoldSusandres modelKtGoldSusandres = BKtGoldSusandres.Find(PrimaryID);
            SetControlValue(modelKtGoldSusandres, txtSustainDayone,"-");
            SetControlValue(modelKtGoldSusandres, txtSustainDaytwo,"-");
            SetControlValue(modelKtGoldSusandres, txtRestainDayone,"-");
            SetControlValue(modelKtGoldSusandres, txtRestainDaytwo,"-");
            SetControlValue(modelKtGoldSusandres, txtSustainWeekone,"-");
            SetControlValue(modelKtGoldSusandres, txtSustainWeektwo,"-");
            SetControlValue(modelKtGoldSusandres, txtRestainWeekone,"-");
            SetControlValue(modelKtGoldSusandres, txtRestainWeektwo,"-");
            if (modelKtGoldSusandres.MParentKtCommCodelistByBreedCode != null)
            {
                ListItem ddlSelectedParentKtCommCodelistByBreedCode = ddlKtCommCodelist.Items.FindByValue(TypeHelper.GetString(modelKtGoldSusandres.MParentKtCommCodelistByBreedCode.CODE_NO));
                if (ddlSelectedParentKtCommCodelistByBreedCode != null)
                {
                    ddlSelectedParentKtCommCodelistByBreedCode.Selected = true;
                }
            }
            //ddlKtCommCodelist.Enabled = false;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.btnSave.Enabled == false)
            {//防用户修改页面按钮disable属性
                return;
            }
            string msg = "";
            #region 接受操作参数
            bool isAdd = false;
            if (StringHelper.Compare(Op, _AddName))
            {
                isAdd = true;
            }
            else if (StringHelper.Compare(Op, _ModifyName))
            {
                isAdd = false;
            }
            else
            {
                return;
            }
            #endregion
            MKtCommCodeList mParentKtCommCodelistByBreedCode = null;
            if (ddlKtCommCodelist.SelectedValue == "")
            {
                msg = "商品代码必须选择" + "\r\n";
            }
            else
            {
                mParentKtCommCodelistByBreedCode = BKtCommCodeList.Find(TypeHelper.GetInt(ddlKtCommCodelist.SelectedValue));
                if (mParentKtCommCodelistByBreedCode == null)
                {
                    msg = "商品代码必须选择" + "\r\n";
                }
            }
            if (!PageValidate.IsDecimalNullable(this.txtSustainDayone.Text))
            {
                msg += "日支持位一不是有效的数字" + "\r\n";
            }
            if (!PageValidate.IsDecimalNullable(this.txtSustainDaytwo.Text))
            {
                msg += "日支持位二不是有效的数字" + "\r\n";
            }
            if (!PageValidate.IsDecimalNullable(this.txtRestainDayone.Text))
            {
                msg += "日阻力位一不是有效的数字" + "\r\n";
            }
            if (!PageValidate.IsDecimalNullable(this.txtRestainDaytwo.Text))
            {
                msg += "日阻力位二不是有效的数字" + "\r\n";
            }
            if (!PageValidate.IsDecimalNullable(this.txtSustainWeekone.Text))
            {
                msg += "周支持位一不是有效的数字" + "\r\n";
            }
            if (!PageValidate.IsDecimalNullable(this.txtSustainWeektwo.Text))
            {
                msg += "周支持位二不是有效的数字" + "\r\n";
            }
            if (!PageValidate.IsDecimalNullable(this.txtRestainWeekone.Text))
            {
                msg += "周阻力位一不是有效的数字" + "\r\n";
            }
            if (!PageValidate.IsDecimalNullable(this.txtRestainWeektwo.Text))
            {
                msg += "周阻力位二不是有效的数字" + "\r\n";
            }
            if (!String.IsNullOrEmpty(msg))
            {
                MessageBox.Show(this, msg);
                return;
            }
            #region 根据操作选项创建实例
            MKtGoldSusandres modelKtGoldSusandres;
            if (isAdd)
            {
                modelKtGoldSusandres = new MKtGoldSusandres();
            }
            else
            {
                modelKtGoldSusandres = BKtGoldSusandres.Find(PrimaryID);
                if (modelKtGoldSusandres == null)
                {
                    return;
                }
            }
            #endregion
            modelKtGoldSusandres.MParentKtCommCodelistByBreedCode = mParentKtCommCodelistByBreedCode;

            SetModelValue(modelKtGoldSusandres, txtSustainDayone);
            SetModelValue(modelKtGoldSusandres, txtSustainDaytwo);
            SetModelValue(modelKtGoldSusandres, txtRestainDayone);
            SetModelValue(modelKtGoldSusandres, txtRestainDaytwo);
            SetModelValue(modelKtGoldSusandres, txtSustainWeekone);
            SetModelValue(modelKtGoldSusandres, txtSustainWeektwo);
            SetModelValue(modelKtGoldSusandres, txtRestainWeekone);
            SetModelValue(modelKtGoldSusandres, txtRestainWeektwo);
            Castle.Components.Validator.RunWhen runWhen = Castle.Components.Validator.RunWhen.Update;
            if (isAdd)
            {
                runWhen = Castle.Components.Validator.RunWhen.Insert;
            }
            bool isSuccess = modelKtGoldSusandres.IsValid(runWhen);
            if (!isSuccess)
            {
                msg = ActiveRecordValidationBaseHelper.GetErrorMsg(modelKtGoldSusandres);
                MessageBox.Show(this, msg);
                return;
            }
            if (isAdd)
            {
                BKtGoldSusandres.Create(modelKtGoldSusandres);
                msg = "添加成功";
                MessageBox.ShowAndRedirect(this, msg, GetListUrl(0));
            }
            else
            {
                Delete(PrimaryID);
                BKtGoldSusandres.Create(modelKtGoldSusandres);
                //BKtGoldSusandres.Update(modelKtGoldSusandres);
                msg = "修改成功";
                MessageBox.ShowAndRedirect(this, msg, GetListUrl(PageIndex));
            }
        }

       
        protected void btnReturn_Click(object sender, EventArgs e)
        {

            if (StringHelper.Compare(Op, _AddName))
            {
                MessageBox.Redirect(this, GetListUrl(this.AspNetPager1.CurrentPageIndex));
            }
            else
            {
                MessageBox.Redirect(this, GetListUrl(PageIndex));
            }
        }
        private void GoServerListUrl(int? pageIndex)
        {
            string url = GetListUrl(pageIndex);
            Response.Redirect(url, true);
        }
        private string GetListUrl(int? pageIndex)
        {
            string op = "?" + "" + _PageIndexName + "=" +int.Parse(ddlKtCommCodelist.SelectedValue);
            string url = "ListEdit.aspx" + op;
            return url;
        }

        protected void ddlKtCommCodelist_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindData();
        }


        public void SetControlValue(object obj, TextBox control, string defaultText)
        {
           WebHelper.SetControlValue(obj, control);
           if (control.Text == "")
           {
               control.Text = defaultText;
           }
           else
           {
               decimal ddd = 0;
               decimal.TryParse(control.Text, out ddd);
               control.Text = ddd.ToString("F0");
           }
        }

        private void SetModelValue(object obj, TextBox control)
        {
            WebHelper.SetModelValue(obj, control);
            
            
        }

    }
}
